package com.example.springboot.dao.imp;

import com.example.springboot.bean.ProductRecord;
import com.example.springboot.dao.ProductRecordDao;
import com.example.springboot.exception.LowStocksException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * Created by tang on 2018/3/8.
 */
@Service
public class ProductRecordDaoImpl implements ProductRecordDao {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public List<ProductRecord> findAll() {
        String sql = "select  * from book_product_records ";
        List<ProductRecord> productRecordList = jdbcTemplate.query(sql, new BeanPropertyRowMapper<ProductRecord>(ProductRecord.class));

        return productRecordList;
    }

    @Override
    public ProductRecord findById(String id) {
        String sql = "select * from book_product_records where id=?";

        ProductRecord productRecord = jdbcTemplate.queryForObject(sql, new String[]{id},
                new BeanPropertyRowMapper<ProductRecord>(ProductRecord.class));
        return productRecord;
    }


    @Override
    public void updateProductRecord(ProductRecord productRecord) {

    }

    @Override
    @Transactional
    public void updateBookStoreNum(int costNum, String name) {
        String sql = "select store_num from book_product_records where book_name=?";
        int storeNum = jdbcTemplate.queryForObject(sql, new String[]{name}, Integer.class);

        //暂时设置每次只能买一本
        if (storeNum - 1 >= 0) {
            sql = "update book_product_records set store_num=store_num-? where book_name=?";
            jdbcTemplate.update(sql, costNum, name);
        } else {
            throw new LowStocksException("BOOK_LOW_STOCKS");
        }
    }
}
